#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc,char * argv[])
{
    if(argc!=3)
    {
        std::cerr<<"Usage: " << argv[0] << " server-ip server-port" << std::endl;
        exit(0);
    }
    std::string serverip=argv[1];   //将ip存入serverip
    uint16_t serverport=std::stoi(argv[2]);   //将端口号从字符串转为整数
    int sockfd=::socket(AF_INET,SOCK_DGRAM,0);

    if(sockfd<0)
    {
        std::cerr << "cteate socket error" << std::endl;
        exit(1);
    }
    
    struct sockaddr_in server;
    memset(&server,0,sizeof(server)); //初始化sockaddr_in结构体，存储地址信息
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str()); //inet_addr 将点分十进制的 IP 地址字符串转换为网络字节序的 32 位整数。
    while(1)
    {
        std::string line;
        std::cout << "Please Enter# ";
        std::getline(std::cin,line);        
        
        int n=sendto(sockfd,line.c_str(),line.size(),0,(struct sockaddr*)&server,sizeof(server));//向服务器发送信息
        if(n>0)
        {
            struct sockaddr_in temp;
            socklen_t len =sizeof(temp);
            char buff[1024];
            int m=recvfrom(sockfd,buff,sizeof(buff)-1,0,(struct sockaddr*)&temp,&len);//接收服务器响应，接收到显示到屏幕上，反之报错
            if(m>0)
            {
                buff[m]=0;// 添加字符串终止符
                std::cout << buff <<std::endl;
            }
            else
            {
                std::cout << "recvfrom error" << std::endl;
                break;
            }
        }
        else
        {
            std::cout << "sendto error" << std::endl;
            break; 
        }
    }
    ::close(sockfd);//在程序结束时关闭套接字，释放资源。
    return 0;
}